#!/usr/bin/env bash
#########################################################################
# File Name   : build.sh
# Author      : seadog
# mail        : seadog0514@163.com
# Version     : 0.8
# Created Time: Thu 2023-10-05 07:00:40(+0800)
#########################################################################

# Usage:

set -euo pipefail

# !!! define docker image version
IMAGE="seadog0514/seadog-dw:v4"

# !!! prepare
{
  function logme() {
    local LOGTYPE=$1
    shift
    local MSGC=$*
    local LOGTIME
    LOGTIME="\e[37m$(date +%H:%M:%S)\e[00m"
    case $LOGTYPE in
      INFO | i) echo -e "$LOGTIME => INFO  ¦ ${MSGC}" ;;
      WARN | w) echo -e "$LOGTIME \e[0;33m=> WARN \e[00m ¦ ${MSGC}" ;;
      DEBUG | d) echo -e "$LOGTIME => DEBUG ¦ ${MSGC}" >&2 ;;
      ERR | e)
        echo -e "$LOGTIME \e[0;31m=> ERROR \e[00m¦ ${MSGC}"
        return 1
        ;;
    esac
  }

  rm -rf docker-build/dw
  mkdir docker-build/dw
  for file in *; do
    [[ $file == 'dw' ]] && continue
    [[ $file == docker-build* ]] && continue
    [[ $file == 'build.sh' ]] && continue
    [[ $file == 'db_sql_bak' ]] && continue
    /bin/cp -rf "$file" ./docker-build/dw
  done
  /bin/cp -rf ./docker-build/startup.sh ./docker-build/dw/startup.sh
  sed -i 's/DEBUG = True/DEBUG = True/' docker-build/dw/pra01/settings.py
}

{
  # sed -i 's/DEBUG = True/DEBUG = False/' ./docker-build/dw/pra01/settings.py

  db_bak="db.sqlite3-bak-$(date +%Y-%m-%d_%H:%M:%S)"
  cp -r /root/docker-volumes/dw-website/_data/db.sqlite3 ./db_sql_bak/"$db_bak"
  cp -r /root/docker-volumes/dw-website/_data/db.sqlite3 ./docker-build/dw/db.sqlite3

  (
    cd ./docker-build
    docker build . --target final -t $IMAGE
  )

  docker rm -fv dw-website || true
  docker volume rm -f dw-website || true

  # sync static files to nginx dir
  # /root/docker-volumes/ng-router/_data/dw-website/statics
  rsync --delete -azH --delay-updates /home/share_samba/django/dw/statics/ /root/docker-volumes/ng-router/_data/dw-website/statics/
}

# !!! test
# python3 manage.py runserver 0.0.0.0:55555
# docker run -itd --restart unless-stopped -v dw-website:/dw -v /home/share_samba/game/dw:/home/share_samba/game/dw -p 55555:55555 --name dw-website --entrypoint sh $IMAGE
# docker run -itd --restart unless-stopped -v dw-website:/dw -v /home/share_samba/game/dw:/home/share_samba/game/dw -p 55555:55555 --name dw-website --entrypoint sh seadog0514/seadog-dw:v2

# !!! production
docker run -itd --restart unless-stopped -v dw-website:/dw -v /home/share_samba/game/dw:/home/share_samba/game/dw -p 55555:55555 --name dw-website $IMAGE
# ->>> docker push seadog0514/seadog-dw:v3

# !!! cleanup
rm -rf ./docker-build/dw
